package edu.ynu.se.xiecheng.achitectureclass.project.controller;

import edu.ynu.se.xiecheng.achitectureclass.project.util.JwtUtils;
import edu.ynu.se.xiecheng.achitectureclass.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
//前端可以登录
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody Map<String, String> loginRequest) throws Exception {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 验证用户名和密码
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));

        // 加载用户信息
        final UserDetails userDetails = userService.loadUserByUsername(username);

        // 生成 JWT Token
        final String token = jwtUtils.generateToken(userDetails);

        // 返回 Token
        return ResponseEntity.ok(Map.of("token", token));
    }
}